package com.ncu.aldl_client;
import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.View;
import android.widget.Toast;

import com.ncu.aldl_client.databinding.ActivityMainBinding;

/**
 * 接收AIDL传过来的值
 */
public class MainActivity extends Activity {
    ActivityMainBinding binding;
    private ICat catService;
    private ServiceConnection conn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        initAIDL();
    }

    private void initAIDL() {
        Intent intent = new Intent();
        intent.setAction("com.example.broadcastreceiverdemo.AIDL_SERVICE");//android5.0后无
//发使用隐式意图启动服务
        intent.setPackage("com.example.broadcastreceiverdemo");//一定是AIDLService包的包名
        //获取远程service的onBind方法返回的对象的代理
        conn = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                //获取远程service的onBind方法返回的对象的代理
                catService = ICat.Stub.asInterface(service);
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                catService = null;
            }
        };
        //绑定远程服务
        bindService(intent, conn, Service.BIND_AUTO_CREATE);
        binding.btGet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if (catService != null) {
                        binding.tvColor.setText(catService.getColor());
                        binding.tvCount.setText(catService.getWeight() + "");
                    } else {
                        Toast.makeText(MainActivity.this, "AIDL传入的数据为空哦！！", Toast.LENGTH_SHORT).show();
                    }
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (conn != null) {
            unbindService(conn);
        }
    }
}